package main

import (
	"bufio"
	"log"
	"os"

	"strings"

	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

type MyMainWindow struct {
	*walk.MainWindow
}

func main() {
	var (
		openAction, showAboutBoxAction *walk.Action
	)
	//StatusBar
	/*
		icon1, err := walk.NewIconFromFile("img/x.ico")
		if err != nil {
			log.Fatal(err)
		}
		icon2, err := walk.NewIconFromFile("img/stop.ico")
		if err != nil {
			log.Fatal(err)
		}
	*/
	var sbi *walk.StatusBarItem
	//statusbar
	log.Println("Hello,world!")
	mw := new(MyMainWindow)
	if err := (MainWindow{
		AssignTo: &mw.MainWindow,
		Title:    "VPN路由生成",
		//ScreenCenter: true, // 屏幕居中不能用
		MinSize: Size{500, 460},
		Layout:  VBox{Spacing: 2}, //VBox{},

		MenuItems: []MenuItem{
			Menu{
				Text: "&File",
				Items: []MenuItem{
					Action{
						AssignTo:    &openAction,
						Text:        "&Open",
						Image:       "img/open.png",
						OnTriggered: mw.openAction_Triggered,
					},
					Separator{}, //分割栏
					Action{
						Text:        "E&xit",
						OnTriggered: func() { mw.Close() },
					},
				},
			},
			Menu{
				Text: "&Help",
				Items: []MenuItem{
					Action{
						AssignTo:    &showAboutBoxAction,
						Text:        "About",
						OnTriggered: mw.showAboutBoxAction_Triggered,
					},
				},
			},
		},
		/*ContextMenuItems: []MenuItem{
			ActionRef{&showAboutBoxAction},	//右键菜单
		},*/
		ToolBar: ToolBar{
			ButtonStyle: ToolBarButtonImageBeforeText,
			Items: []MenuItem{
				Separator{},            //分割栏
				ActionRef{&openAction}, //一个按钮，调用的是菜单的按钮
				Action{ //为Menu则生成子菜单，为Action则只是一个按钮
					Text:        "New A",
					Image:       "img/document-new.png",
					OnTriggered: mw.openAction_Triggered,
				},
				Separator{},
				Action{
					Text:  "E&xit",
					Image: "img/system-shutdown.png",
					//Enabled:     Bind("isSpecialMode && enabledCB.Checked"),
					OnTriggered: func() { mw.Close() },
				},
			},
		},
		StatusBarItems: []StatusBarItem{
			StatusBarItem{
				AssignTo: &sbi,
				//Icon:     icon1,
				Text:  "click",
				Width: 100,
				OnClicked: func() {
					if sbi.Text() == "click" {
						sbi.SetText("again")
					} else {
						sbi.SetText("click")
					}
				},
			},
			StatusBarItem{
				Text:        "left",
				Width:       200,
				ToolTipText: "no tooltip for me",
			},
			StatusBarItem{
				//Icon:        icon1,
				Text:        "hello",
				Width:       200,
				ToolTipText: "An icon with a tooltip",
			},
		},
	}.Create()); err != nil {
		log.Fatal(err)
	}
	mw.Run()
}

func (mw *MyMainWindow) showAboutBoxAction_Triggered() {
	walk.MsgBox(mw, "About", "Walk Actions Example", walk.MsgBoxIconInformation)
}

func (mw *MyMainWindow) openAction_Triggered() {
	if err := mw.openFile(); err != nil {
		log.Print(err)
	}
	//walk.MsgBox(mw, "Open", "打开文件", walk.MsgBoxIconInformation)
}
func (mw *MyMainWindow) openFile() error {
	dlg := new(walk.FileDialog)

	//var te *walk.TextEdit

	//dlg.FilePath = Mw.prevFilePath
	dlg.Filter = "txt Files (*.txt)|*.txt"
	dlg.Title = "选择导入的国内IP段文件"

	if ok, err := dlg.ShowOpen(mw); err != nil {
		return err
	} else if !ok {
		return nil
	}
	//walk.MsgBox(mw, "Open", "导入文件路径："+dlg.FilePath, walk.MsgBoxIconInformation)
	clTxtFile(dlg.FilePath)
	return nil
}

func clTxtFile(filePath string) (err error) {
	//读文件
	f, err := os.Open(filePath)
	defer f.Close() //任务结束后要关闭这个文件（通常这个操作应该在 Open操作后立即使用 defer 来完成）。
	if err != nil {
		panic(err)
	}
	//写文件
	wf, err := os.Create("route.cmd")
	defer wf.Close()
	if err != nil {
		panic(err)
	}
	//一行行读取文件内容
	scanner := bufio.NewScanner(f)
	w := bufio.NewWriter(wf)
	var s string
	for scanner.Scan() {
		s = scanner.Text()                  //读一行文本内容
		s, _ = clTxt(s)                     //处理IP段地址表，改成WINDOWS添加路由的字符
		i, err := w.WriteString(s + "\r\n") //写入文件，经scanner处理的没有了换行，要添加换行，i表示写入了多少字节
		log.Println(s, i)                   // Println will add back the final '\n'
		if err != nil {
			log.Println("err:", err.Error)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Println("reading standard input:", err)
	}
	w.Flush() //写入文件缓冲区
	/*	r := bufio.NewReader(f)
		    if e != nil {
		        panic(e)
		    }

			i := 1
		    for {
		        //buf,err := r.ReadBytes('\n')
		        buf,err := r.ReadString('\n')
		        if err == io.EOF{
		            break
		        }
		        if *num_flag{
		            fmt.Fprintf(os.Stdout,"%5d %s",                    i,buf)
		            i++
		        }else{
		            fmt.Fprintf(os.Stdout,"%s",buf)
		        }

		    }
	*/
	return err
}

func clTxt(ins string) (outs string, err error) {
	var (
		strSplit []string
		ipRange  string
		maskBit  string
		mask     string
	)
	strSplit = strings.Split(ins, "/")
	ipRange = strSplit[0]
	maskBit = strSplit[1]
	//掩码位转成掩码字符
	mask = maskBit
	outs = "route add " + ipRange + " mask " + mask + " ip"
	return outs, err
}
